//
//  SearchViewController.m
//  jiyujiaProgram
//
//  Created by SSIC on 16/1/10.
//  Copyright © 2016年 中良 赵. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchCell.h"
#import "TSearchModel.h"
#import "CSearchModel.h"

#import "ScheduleDetailViewController.h"
#import "InfoViewController.h"


@interface SearchViewController () <UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>

@end

@implementation SearchViewController
{
    UIView *_fastMenu;
    UIView *_gestureAssistView;     //辅助手势View，用以取消各种键盘、菜单
    UITextField *_searchTextField;
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    BOOL isTeacher;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatNavigationBarWithImage:nil title:nil];
    [self creatNavigationBarLeftItemWithLeftTitle:@"教师" LeftImage:nil];
    [self creatNavigationBarRightItemWithRightTitle:@"取消" RightImage:nil];
    
    [self creatSearchBar];
    [self creatFastMenu];
    [self creatTableView];
}


- (void)leftBtnClick:(id)leftSender
{
    [_searchTextField resignFirstResponder];
    if (!_gestureAssistView) {
        _gestureAssistView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ECSCREEN_W, ECSCREEN_H)];
        _gestureAssistView.backgroundColor = ECCOLOR(0, 0, 0, .3f);
        UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(event:)];
        [_gestureAssistView addGestureRecognizer:tapGesture];
        [self.view addSubview:_gestureAssistView];
    }else
    {
        _gestureAssistView.hidden = NO;
    }
    
    if (_fastMenu.hidden) {
        //动画
        _fastMenu.hidden = NO;
        _fastMenu.frame = CGRectMake(0, 60, 120, 0);
        [UIView animateWithDuration:0.4 animations:^{
            _fastMenu.frame = CGRectMake(0, 60, 120, 80);
        }];
        [self.view bringSubviewToFront:_fastMenu];
    }else
    {
        [UIView animateWithDuration:0.4 animations:^{
            _fastMenu.frame = CGRectMake(0, 60, 120, 0);
        } completion:^(BOOL finished) {
            _fastMenu.hidden = YES;
            _gestureAssistView.hidden = YES;
        }];
    }
}


- (void)event:(UITapGestureRecognizer *)gesture
{
    [UIView animateWithDuration:0.4 animations:^{
        _fastMenu.frame = CGRectMake(0, 60, 120, 0);
    } completion:^(BOOL finished) {
        _fastMenu.hidden = YES;
        _gestureAssistView.hidden = YES;
    }];
}

- (void)menuBtnClick:(UIButton *)button
{
    [UIView animateWithDuration:0.4 animations:^{
        _fastMenu.frame = CGRectMake(0, 60, 120, 0);
    } completion:^(BOOL finished) {
        _fastMenu.hidden = YES;
        _gestureAssistView.hidden = YES;
    }];
    
    self.leftLabel.text = button.titleLabel.text;
    isTeacher = button.tag == 100?YES:NO;
    _searchTextField.text = @"";
    if (_dataArray) {
        [_dataArray removeAllObjects];
    }else{
        _dataArray = [[NSMutableArray alloc] init];
    }
    [_tableView reloadData];
}


- (void)rightBtnClick:(id)rightSender
{
    [_searchTextField resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_searchTextField resignFirstResponder];
}


- (void)creatSearchBar
{
    _searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(ECNavcLeftButtonFrame)+3, 25, ECSCREEN_W-2*CGRectGetWidth(ECNavcLeftButtonFrame)-6, 30)];
    _searchTextField.layer.cornerRadius = 5;
    _searchTextField.layer.borderColor = [UIColor colorWithPatternImage:ECIMAGENAME(@"search_bg.png")].CGColor;
    _searchTextField.layer.borderWidth = .7f;
    _searchTextField.borderStyle = UITextBorderStyleRoundedRect;
    _searchTextField.placeholder = @"教师、课程";
    _searchTextField.delegate = self;
    _searchTextField.backgroundColor = [UIColor colorWithPatternImage:ECIMAGENAME(@"search_bg.png")];
    _searchTextField.textColor = [UIColor whiteColor];
    _searchTextField.font = [UIFont fontWithName:SystemFont size:14.f];
    _searchTextField.clearsOnBeginEditing = YES;
    [self.navcImageView addSubview:_searchTextField];
    
    //搜索按钮图片
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_searchTextField.frame) - 23, 31, 20, 20)];
    imageView.image = [UIImage imageNamed:@"search_button.png"];
    imageView.userInteractionEnabled = YES;
    [self.navcImageView addSubview:imageView];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(creatHttpRequest:) name:UITextFieldTextDidChangeNotification object:_searchTextField];
}



- (void)creatHttpRequest:(NSNotification *)noti
{
    UITextField *textField = [noti object];
    
    NSDictionary * param = @{
                             @"keyword":textField.text,
                             @"pageIndex":@"0",
                             @"pageSize":@"999",
                             };
    
    if (isTeacher) {
        [[HttpManager defaultManager] postRequestToUrl:RequestURL(SEARCH_T) params:param complete:^(BOOL successed, NSDictionary *result) {
            if (successed) {
                [TSearchModel setupObjectClassInArray:^NSDictionary *{
                    return @{
                             @"data":@"TeacherModel",
                             };
                }];
                
                if (_dataArray) {
                    [_dataArray removeAllObjects];
                }else{
                    _dataArray = [[NSMutableArray alloc] init];
                }
                
                TSearchModel *searchModel = [[TSearchModel alloc] init];
                searchModel = [TSearchModel objectWithKeyValues:result];
                [_dataArray addObjectsFromArray:searchModel.data];
                [_tableView reloadData];
            }
        }];
    }else{
        [[HttpManager defaultManager] postRequestToUrl:RequestURL(SEARCH_C) params:param complete:^(BOOL successed, NSDictionary *result) {
            if (successed) {
                [CSearchModel setupObjectClassInArray:^NSDictionary *{
                    return @{
                             @"data":@"ScheduleDetailModel",
                             };
                }];
                
                if (_dataArray) {
                    [_dataArray removeAllObjects];
                }else{
                    _dataArray = [[NSMutableArray alloc] init];
                }
                
                CSearchModel *searchModel = [[CSearchModel alloc] init];
                searchModel = [CSearchModel objectWithKeyValues:result];
                [_dataArray addObjectsFromArray:searchModel.data];
                [_tableView reloadData];
            }
        }];
    }
}



- (void)creatFastMenu
{
    _fastMenu = [[UIView alloc] initWithFrame:CGRectMake(0, 60, 120, 80)];
    _fastMenu.hidden = YES;
    _fastMenu.clipsToBounds = YES;
    _fastMenu.layer.cornerRadius = 5;
    _fastMenu.backgroundColor = ECCOLOR(0, 0, 0, .8f);
    [self.view addSubview:_fastMenu];
    
    NSArray *titleArr = @[@"教师",@"课程"];
    for (int i = 0; i < titleArr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 40*i, 120, 40);
        [button setTitle:titleArr[i] forState:UIControlStateNormal];
        [button setTitleColor:ECCOLOR(255, 255, 255, 1) forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:13.f];
        button.tag = 100+i;
        [button addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0) {
            [self menuBtnClick:button];
        }
        [_fastMenu addSubview:button];
    }
    
    UIView *speraLine = [[UIView alloc] initWithFrame:CGRectMake(0, 40, 120, .5f)];
    speraLine.backgroundColor = ECCOLOR(255, 255, 255, .3);
    [_fastMenu addSubview:speraLine];
}



- (void)creatTableView
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ECSCREEN_W, ECSCREEN_H - 64) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    _tableView.tableFooterView = [[UIView alloc]init];
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [_tableView addGestureRecognizer:tableViewGesture];
}


- (void)tableViewTouchInSide
{
    [_searchTextField resignFirstResponder];
}

#pragma mark - tableViewNumberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}


#pragma mark - tableViewHeightForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.f;
}


#pragma mark - tableViewCellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseIdentifier = @"searchCell";
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (nil == cell) {
        NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"SearchCell" owner:nil options:nil];
        for (NSObject *obj in arr) {
            if ([obj isKindOfClass:[SearchCell class]]) {
                cell = (SearchCell *)obj;
                if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                    [cell setSeparatorInset:UIEdgeInsetsZero];
                }
                if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                    [cell setLayoutMargins:UIEdgeInsetsZero];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                break;
            }
        }
    }
    [cell setCellWithModel:_dataArray WithIndexPath:indexPath WithSelect:isTeacher];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchTextField resignFirstResponder];
    if (isTeacher) {
        TeacherModel *model = _dataArray[indexPath.row];
        InfoViewController *vc = [[InfoViewController alloc] init];
        vc.memberId = model.member_Id;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        ScheduleDetailModel *model = _dataArray[indexPath.row];
        ScheduleDetailViewController *vc = [[ScheduleDetailViewController alloc] init];
        vc.course_Id = model.course_Id;
        vc.isStudent = NO;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
